﻿using System;
using System.Data;
using System.IO;
using System.Windows.Forms;
using HRM.HRMServiceProxy;
using WeifenLuo.WinFormsUI.Docking;

namespace HRM
{
    public partial class frmEducationList : DockContent
    {
        EducationClient _wcfEducation;
        MainServiceClient wcfMain;
        int pageSize = UIParamater.pageSize;
        int currPage = 0;
        int itemCount = 0;
        int totalPage = 0;
        int _EducationID = 0;
        int department_ID;
        int branch_ID;
        int _EmployeeID = 0;
        RoleRightInfo listRole;
        bool _loadedData = false;
        public frmEducationList()
        {
            InitializeComponent();
            LoadLanguage();
            _wcfEducation = Service.Education();
            wcfMain = Service.MainService();
            UISetting.LoadMonths(ref cboMonth);
            BuildVoucherGrid();
            UISetting.LoadTreeView3(ref tvBranch);
            //cboMonth.ComboBox.SelectedValue = Convert.ToInt32(DateTime.Now.Month);

            UISetting.LoadYears(ref cboYear);
            //cboYear.ComboBox.SelectedValue = Convert.ToInt32(DateTime.Now.Year);


            listRole = UIParamater.Quyen_CacKhoaDaoTao;
            if (!listRole._create)
                btnNew.Enabled = false;
            if (!listRole._delete)
                btnDel.Enabled = false;
            if (!listRole.Update)
            {
                this.btnEdit.Image = global::HRM.Properties.Resources.app;
                this.btnEdit.Tag = "xem";
            }
            LoadData();

        }
        void LoadLanguage()
        {
            if (this.Tag != null)
                this.Text = this.TabText = UpdateUI.GetString(this.Tag.ToString());
            UpdateUI.Load_ToolStrip(ref toolStrip1);
        }
        private void PageIndex()
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage == 0)
                lblPageIndex.Text = "0" + "/" + totalPage.ToString();
            else
                lblPageIndex.Text = (currPage + 1).ToString() + "/" + totalPage.ToString();
        }

        private void BuildVoucherGrid()
        {
            UISetting.AddColumn(ref dgvList, "Education_ID", "Mã chính", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "Education_EmployeeID", "Mã nhân viên", "", 1, false, true);
            UISetting.AddColumn(ref dgvList, "RowNumber", UpdateUI.GetString("stt"), "C", 50, true, true);
            UISetting.AddColumn(ref dgvList, "FullName", UpdateUI.GetString("hovaten"), "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Name", UpdateUI.GetString("khoadaotao"), "", 130, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Kind", UpdateUI.GetString("loaihinhdaotao"), "", 130, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Major", UpdateUI.GetString("chuyennganh"), "", 130, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Foreign", UpdateUI.GetString("nuocngoai"), "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Place", "Nơi đào tạo", "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_FromDate", UpdateUI.GetString("ngaybatdau"), "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Time", UpdateUI.GetString("thoigian"), "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_DateIssue", UpdateUI.GetString("ngaycap"), "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_AuthorIssue", UpdateUI.GetString("noicap"), "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Rank", UpdateUI.GetString("xeploai"), "", 120, true, true);
            UISetting.AddColumn(ref dgvList, "Education_Description", UpdateUI.GetString("ghichu"), "", 160, true, true);
        }
        private void LoadData()
        {
            int _month = Convert.ToInt32(cboMonth.ComboBox.SelectedValue);
            int _year = Convert.ToInt32(cboYear.Text);

            DataSet _ds = _wcfEducation.Education_GetList(out itemCount, currPage, pageSize, branch_ID, department_ID, _month, _year);
            int n = _ds.Tables[0].Rows.Count;
            PageIndex();
            dgvList.Rows.Clear();
            for (int i = 0; i < n; i++)
            {
                dgvList.Rows.Insert(i, 1);
                dgvList.Rows[i].Cells["Education_ID"].Value = _ds.Tables[0].Rows[i]["Education_ID"].ToString();
                dgvList.Rows[i].Cells["Education_EmployeeID"].Value = _ds.Tables[0].Rows[i]["Education_EmployeeID"].ToString();
                dgvList.Rows[i].Cells["RowNumber"].Value = _ds.Tables[0].Rows[i]["RowNumber"].ToString();
                dgvList.Rows[i].Cells["FullName"].Value = _ds.Tables[0].Rows[i]["Employee_FullName"].ToString();
                dgvList.Rows[i].Cells["Education_Name"].Value = _ds.Tables[0].Rows[i]["Education_Name"].ToString();
                dgvList.Rows[i].Cells["Education_Kind"].Value = _ds.Tables[0].Rows[i]["Education_Kind"].ToString();
                dgvList.Rows[i].Cells["Education_Major"].Value = _ds.Tables[0].Rows[i]["Education_Major"].ToString();
                dgvList.Rows[i].Cells["Education_Foreign"].Value = _ds.Tables[0].Rows[i]["Education_Foreign"].ToString();
                dgvList.Rows[i].Cells["Education_Place"].Value = _ds.Tables[0].Rows[i]["Education_Place"].ToString();
                if (_ds.Tables[0].Rows[i]["Education_FromDate"] != DBNull.Value)
                    dgvList.Rows[i].Cells["Education_FromDate"].Value = Convert.ToDateTime(_ds.Tables[0].Rows[i]["Education_FromDate"]).ToString("dd/MM/yyyy");
                else
                    dgvList.Rows[i].Cells["Education_FromDate"].Value = "";
                dgvList.Rows[i].Cells["Education_Time"].Value = _ds.Tables[0].Rows[i]["Education_Time"].ToString();
                if (_ds.Tables[0].Rows[i]["Education_DateIssue"] != DBNull.Value)
                    dgvList.Rows[i].Cells["Education_DateIssue"].Value = Convert.ToDateTime(_ds.Tables[0].Rows[i]["Education_DateIssue"]).ToString("dd/MM/yyyy");
                else
                    dgvList.Rows[i].Cells["Education_DateIssue"].Value = "";
                dgvList.Rows[i].Cells["Education_AuthorIssue"].Value = _ds.Tables[0].Rows[i]["Education_AuthorIssue"].ToString();
                dgvList.Rows[i].Cells["Education_Rank"].Value = _ds.Tables[0].Rows[i]["Education_Rank"].ToString();
                dgvList.Rows[i].Cells["Education_Description"].Value = _ds.Tables[0].Rows[i]["Education_Description"].ToString();
            }
            _loadedData = true;
        }



        private void btnNew_Click(object sender, EventArgs e)
        {
            if (!listRole.Create)
            {
                MessageBox.Show(UpdateUI.GetString("khongcoquyenthemmoi"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }
            Form f = new frmEducationInfo(0, 0, listRole);
            if (f.ShowDialog(this) == DialogResult.OK)
            {
                LoadData();
            }
        }

        private void btnEdit_Click(object sender, EventArgs e)
        {

            if (dgvList.SelectedRows.Count > 0)
            {
                if (listRole.Update || listRole.View)
                {
                    _EducationID = Convert.ToInt32(dgvList.CurrentRow.Cells["Education_ID"].Value);
                    _EmployeeID = Convert.ToInt32(dgvList.CurrentRow.Cells["Education_EmployeeID"].Value);
                    Form f = new frmEducationInfo(_EducationID, _EmployeeID, listRole);
                    if (f.ShowDialog(this) == DialogResult.OK)
                    {
                        LoadData();
                    }
                }
                else
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxem"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
        }

        private void btnDel_Click(object sender, EventArgs e)
        {
            if (dgvList.SelectedRows.Count > 0)
            {
                if (!listRole.Delete)
                {
                    MessageBox.Show(UpdateUI.GetString("khongcoquyenxoa"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    return;
                }
                _EducationID = Convert.ToInt32(dgvList.CurrentRow.Cells["Education_ID"].Value);
                if (MessageBox.Show(UpdateUI.GetString("bancochacchanxoa"), UIParamater.TitleProject, MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                {
                    if (_wcfEducation.Education_Delete(_EducationID))
                    {
                        Program.taskbarNotifier.Show(UIParamater.TitleProject, UpdateUI.GetString("xoathanhcong"), UIParamater.TIME_MOVE_UP, UIParamater.TIME_SHOW, UIParamater.TIME_MOVE_DOWN);
                        LoadData();
                    }
                    else
                    {
                        MessageBox.Show(UpdateUI.GetString("xoakhongthanhcong"), UIParamater.TitleProject, MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    }
                }
            }
        }

        private void btnFisrt_Click(object sender, EventArgs e)
        {
            currPage = 0;
            LoadData();
        }

        private void btnNext_Click(object sender, EventArgs e)
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage > 0 && currPage != totalPage - 1)
                currPage++;
            LoadData();
        }

        private void btnPrevious_Click(object sender, EventArgs e)
        {
            if (currPage != 0)
                currPage--;
            LoadData();
        }

        private void btnLast_Click(object sender, EventArgs e)
        {
            totalPage = itemCount % pageSize > 0 ? (itemCount / pageSize) + 1 : (itemCount / pageSize);
            if (totalPage != 0)
                currPage = totalPage - 1;
            LoadData();
        }

        private void dgvList_CellDoubleClick(object sender, DataGridViewCellEventArgs e)
        {
            if (e.RowIndex >= 0)
                btnEdit_Click(null, null);
        }

        private void frmEducationList_KeyUp(object sender, KeyEventArgs e)
        {
            switch (e.KeyCode)
            {
                case Keys.Escape:
                    this.Close();
                    this.Dispose();
                    break;
                case Keys.F2:
                    btnNew_Click(null, null);
                    break;
                case Keys.F3:
                    btnEdit_Click(null, null);
                    break;
            }
        }

        private void tvBranch_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (e.Node.Level == 0)
            {
                if (Program.isAdmin || Program.isViewAll)
                    branch_ID = 0;
                else
                    branch_ID = Program.intBranchID;
                department_ID = 0;
                LoadData();
            }
            else if (e.Node.Level == 1)
            {
                branch_ID = Convert.ToInt32(e.Node.Tag);
                department_ID = 0;
                currPage = 0;
                LoadData();
            }
            else if (e.Node.Level >= 2)
            {
                department_ID = Convert.ToInt32(e.Node.Tag);
                branch_ID = Convert.ToInt32(e.Node.Parent.Tag);
                currPage = 0;
                LoadData();
            }
        }

        private void cboYear_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                currPage = 0;
                LoadData();
            }
        }

        private void cboMonth_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (_loadedData)
            {
                currPage = 0;
                LoadData();
            }
        }

        private void frmEducationList_Activated(object sender, EventArgs e)
        {
            LoadLanguage();
            dgvList.Columns["RowNumber"].HeaderText = UpdateUI.GetString("stt");
            dgvList.Columns["FullName"].HeaderText = UpdateUI.GetString("hovaten");
            dgvList.Columns["Education_Name"].HeaderText = UpdateUI.GetString("khoadaotao");
            dgvList.Columns["Education_Kind"].HeaderText = UpdateUI.GetString("loaihinhdaotao");
            dgvList.Columns["Education_Major"].HeaderText = UpdateUI.GetString("chuyennganh");
            dgvList.Columns["Education_Foreign"].HeaderText = UpdateUI.GetString("nuocngoai");
            dgvList.Columns["Education_Place"].HeaderText = "Nơi đào tạo";
            dgvList.Columns["Education_FromDate"].HeaderText = UpdateUI.GetString("ngaybatdau");
            dgvList.Columns["Education_Time"].HeaderText = UpdateUI.GetString("thoigian");
            dgvList.Columns["Education_DateIssue"].HeaderText = UpdateUI.GetString("ngaycap");
            dgvList.Columns["Education_AuthorIssue"].HeaderText = UpdateUI.GetString("noicap");
            dgvList.Columns["Education_Rank"].HeaderText = UpdateUI.GetString("xeploai");
            dgvList.Columns["Education_Description"].HeaderText = UpdateUI.GetString("ghichu");
        }

        private void frmEducationList_FormClosing(object sender, FormClosingEventArgs e)
        {
            _wcfEducation.Close();
            wcfMain.Close();
        }

        private void btnExcel_Click(object sender, EventArgs e)
        {
            string _fileName = "";
            string branchName = "";
            string departmentName = "";
            _fileName = "tmpEdu.xls";
            int _month = Convert.ToInt32(cboMonth.ComboBox.SelectedValue);
            int _year = Convert.ToInt32(cboYear.Text);
            BranchClient wcfBranch = Service.Branch();
            DepartmentClient wcfDepartment = Service.Department();
            if (branch_ID > 0)
            {
                branchName = wcfBranch.Branch_GetInfo(branch_ID).Name;
            }

            if (department_ID > 0)
            {
                departmentName = wcfDepartment.Department_GetInfo(department_ID).Name;
            }
            try
            {
                DataSet ds = _wcfEducation.Education_GetList(out itemCount, currPage, pageSize, branch_ID, department_ID, _month, _year);
                if (ds.Tables.Count > 0)
                {
                    ds.Tables[0].Columns.Remove("Education_ID");
                    ds.Tables[0].Columns.Remove("Education_EmployeeID");
                    ds.Tables[0].Columns.Remove("Branch_ID");
                    ds.Tables[0].Columns.Remove("Department_ID");
                    ds.Tables[0].Columns["Rownumber"].Caption = "STT";
                    ds.Tables[0].Columns["Employee_FullName"].Caption = "Họ và tên";
                    ds.Tables[0].Columns["Education_Name"].Caption = "Khóa đào tạo";
                    ds.Tables[0].Columns["Education_Kind"].Caption = "Loại hình đào tạo";
                    ds.Tables[0].Columns["Education_Major"].Caption = "Chuyên ngành";
                    ds.Tables[0].Columns["Education_Foreign"].Caption = "Đào tạo nước ngoài";
                    ds.Tables[0].Columns["Education_Place"].Caption = "Nơi đào tạo";
                    ds.Tables[0].Columns["Education_FromDate"].Caption = "Ngày bắt đầu";
                    ds.Tables[0].Columns["Education_Time"].Caption = "Thời gian";
                    ds.Tables[0].Columns["Education_DateIssue"].Caption = "Ngày cấp";
                    ds.Tables[0].Columns["Education_AuthorIssue"].Caption = "Nơi cấp";
                    ds.Tables[0].Columns["Education_Rank"].Caption = "Xếp loại";
                    ds.Tables[0].Columns["Education_Description"].Caption = "Ghi chú";

                    ReadExcelFile.exportToExcelForEmployeeList("DANH SÁCH QUÁ TRÌNH ĐÀO TẠO", branchName, departmentName, ds, Path.GetTempPath() + "\\" + _fileName);

                    try
                    {
                        System.Diagnostics.Process.Start(Path.GetTempPath() + "\\" + _fileName);
                    }
                    catch (Exception)
                    {
                        MessageBox.Show("Không mở được File \n" + Path.GetTempPath() + "\\" + _fileName, "Thông báo");
                    }
                }
            }
            catch (Exception)
            {
                MessageBox.Show("File " + Path.GetTempPath() + "\\" + _fileName + " đang được mở bằng một ứng dụng khác.\nHãy chọn file khác!", "Thông báo");
            }
        }
    }
}
